package logicaPresentacion;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import logicaNegocio.GestionAdministrador;
import logicaNegocio.GestionAlumnos;
import logicaNegocio.Grado;


public class VerGrados extends JInternalFrame implements ActionListener,Observer
{	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private GestionAdministrador gAd;
	private GestionAlumnos gA;
	private String eleccion, dni;
	private JTable tbGrados;	
    private JScrollPane scrollPane; 
    private JPanel jpBotones;
	private TablaGrados tabla = null;        
	private JButton aceptar, cancelar, borrar;
	private ClaseAObservar observable;
	private Map<String, Grado> grados;
	private Grado G;
		
	public VerGrados(GestionAdministrador gAd, GestionAlumnos gA, String eleccion,String dni, ClaseAObservar observable)
	{
		
		super("Grados", 
	              true, 
	              false, 
	              true, 
	              true);
		setVisible(true);
		setSize(800,300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.inicializarSubComponentes();
		
		this.eleccion = eleccion;
		this.dni= dni;
		this.gAd = gAd;
		this.gA = gA;
		this.observable = observable;
		
		blnCargarFormulario();
		
	}
	
	public void blnCargarFormulario()
	{		
		crearTablaProductos();
		this.setLocation(200,200);
		this.setVisible(true);
		inicializarSubComponentes();
	}
	
	public void crearTablaProductos()
	{
		
		tbGrados=null;
		tabla=new TablaGrados();
		
		if ((eleccion == "Administrador") ||(eleccion == "Borrar"))
		{
			tabla.crearTabla(gAd.getGrados());
		}
		if (eleccion.equals("Alumno"))
		{
			tabla.crearTabla(gA.getGrados());
		}
		
		tbGrados = new JTable(tabla);
		tbGrados.setPreferredScrollableViewportSize(new Dimension(500, 70));
		tbGrados.setFillsViewportHeight(true);
		tbGrados.setEnabled(true);
		tbGrados.setRowSelectionAllowed(true);
		tabla.fireTableDataChanged();
				
	}	
	public void inicializarSubComponentes()
	{		
		try
		{
			
			scrollPane= new JScrollPane(tbGrados);

			this.getContentPane().setLayout(new BorderLayout());
	        this.getContentPane().add(scrollPane,"Center");
	        
	        Box boxbotones;
	        if(eleccion.equals("Borrar"))
	        {
	        	borrar=new JButton("Borrar");
	        	borrar.addActionListener(this);
				cancelar=new JButton("Cancelar");
				cancelar.addActionListener(this);
		      
		        boxbotones = Box.createHorizontalBox();
		        boxbotones.add(borrar);
		        Box.createHorizontalStrut(20);
		        boxbotones.add(cancelar);
		        
		        jpBotones=new JPanel();
				jpBotones.setLayout(new FlowLayout());
				jpBotones.add(boxbotones);
	        }
	        else
	        {
	        
		        aceptar=new JButton("Aceptar");
				aceptar.addActionListener(this);
				jpBotones=new JPanel();
				jpBotones.setLayout(new FlowLayout());
				jpBotones.add(aceptar);
	        }
			
			this.getContentPane().add(jpBotones,"South");
		}
		catch(Exception e)
		{
		}
		
	}
		
	public void actionPerformed(ActionEvent e)
	{	
		if (e.getSource() instanceof JButton) 
		{
			JButton btnPulsado=(JButton)e.getSource();

			if ((btnPulsado==aceptar)||(btnPulsado==cancelar)) 
			{
				dispose();
			}
			if(btnPulsado==borrar)
			{
				int row = tbGrados.getSelectedRow();
				if(row>=0)
				{
					grados = gAd.getGrados();
					
					G = grados.get(tbGrados.getValueAt(row, 0));//4 es el dni

					gAd.borrarGrado(G);

					observable.setTabla();
					
					JOptionPane.showMessageDialog(null, "Tupla Borrada");
					dispose();
				}
				else
				{
					JOptionPane.showMessageDialog(null, "Debe seleccionar una fila si quiere borrar una tupla");          
				}
			}						
		}
	}

	public void update(Observable o, Object arg) 
	{	
		tbGrados=null;
		tabla.crearTabla(gAd.getGrados());
		tbGrados = new JTable(tabla);
		tbGrados.setPreferredScrollableViewportSize(new Dimension(500, 70));
		tbGrados.setFillsViewportHeight(true);
		tbGrados.setEnabled(true);
		tbGrados.setRowSelectionAllowed(true);
		tabla.fireTableDataChanged();		
	}

	class TablaGrados extends AbstractTableModel
    {
 		/**
 		 * 
 		 */
		private static final long serialVersionUID = 3783586734941958199L;
		private String[] columnNames = {"ID_Grado","Nombre Grado","Caracteristicas de Grado", "InforEconomica","Nombre del campus"};
		private Object[][] data;
	        
	    public void crearTabla(Map<String,Grado> grados)
	    {

			int cont;
			
			if ((eleccion.equals("Administrador"))||(eleccion.equals("Borrar")))
			{
				int filas = grados.size();
				data=new Object[filas][];
				cont=0;
				grados = gAd.ordenarGrados(grados);
				
	    		for (Map.Entry<String, Grado> entry : grados.entrySet())
	    		{
	    			
	    			Grado g = grados.get(entry.getKey());
	    			Object[]a={
	    					   new String(Integer.toString(g.getID())),
	    					   new String(g.getNombreGrado()),
	    					   new String(g.getCaracteristicasGrado()),
	    					   new Double(g.getInforEconomica()),
	    					   new String(g.getCampus().getNombreCampus()),
	
	    			};
	    			data[cont]=a;
	    			cont++;
	    		} 
			}
			
			if (eleccion.equals("Alumno"))
			{
				cont = 0;
	    		data=new Object[1][];

				Grado g = gA.verMisGrados(dni);  
				
				Object[]a={
						   new String(Integer.toString(g.getID())),
						   new String(g.getNombreGrado()),
						   new String(g.getCaracteristicasGrado()),
						   new Double(g.getInforEconomica()),
						   new String(g.getCampus().getNombreCampus()),
	
				};
				data[0]=a;
			
			}
	    }
	    
	    public int getColumnCount() 
	    {
	        return columnNames.length;
	    }
	
	    public int getRowCount() {
	        return data.length;
	    }
	
	    public String getColumnName(int col) 
	    {
	        return columnNames[col];
	    }
	
	    public Object getValueAt(int row, int col) 
	    {
	        return data[row][col];
	    }
	}
}
